/**
 * @author: yyq
 * @date: 2025年3月13日 11:54:30
 * @description: 
 */
package com.sheepone.monitor.handler;

import com.sheepone.monitor.codec.SheeponeContentOutboundConverter;
import com.sheepone.monitor.codec.SheeponePackage;
import com.sheepone.monitor.enums.SerializationAlgorithmsEnum;
import com.sheepone.monitor.enums.SheeponePackageTypeEnum;
import com.sheepone.webdev.log.WebDevLogger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * @author: yyq
 * @date: 2025年3月13日 11:54:30
 * @description:
 */
public abstract class AbstractSheeponeContentOutboundHandler<W> extends ChannelOutboundHandlerAdapter
        implements SheeponeContentOutboundConverter<W> {
    private SheeponePackageTypeEnum type;
    private SerializationAlgorithmsEnum serialization;
    private static WebDevLogger logger = WebDevLogger.getLogger(AbstractSheeponeContentOutboundHandler.class);

    public AbstractSheeponeContentOutboundHandler(SheeponePackageTypeEnum type,
            SerializationAlgorithmsEnum serialization) {
        this.type = type;
        this.serialization = serialization;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof SheeponePackage) {
            ctx.write(msg, promise);
            return;
        }
        Object obj = msg;
        try {
            W content = (W) msg;
            if (content != null) {
                SheeponePackage sp = new SheeponePackage();
                sp.setType(type);
                sp.setSerialization(this.serialization);
                sp.setContent(toBytes(content, this.serialization));
                obj = sp;
            }
        } catch (Exception e) {
            if (!(e instanceof ClassCastException)) {
                logger.error("{} write error", this.getClass().getName(), e.getMessage());
            }
        } finally {
            ctx.write(obj, promise);
        }
    }

}
